/**
 * Created by Lesh on 30.11.13.
 */

var image = {
	index: function(){
		this.getPage(this.page, this.pageCount);
		this.imageLoader("#content div #image");
		$( "body" ).on( "click", "#page", function(event) {
			event.preventDefault();
			history.pushState({ path: this.path }, '', $(this).attr("href"));
			image.page = $(this).attr("page");
			$.post('/a/get_page', {page: image.page}, function(data) {
				$('#content').html(data.content);
				image.getPage(image.page, image.pageCount);
				image.imageLoader("#content div #image");
			}, 'json');
		});
	},
	imageLoader: function(node){
		var i = 0;
		var arr = [];
		$( node ).on( "load", function() {
			$(this).attr('done', ++i);
			arr.push(this);
			if (i == image.itemPage || image.itemCount == (image.page - 1) * image.itemPage + i)
			{
				var j = 0;
				$.each(image.shuffle(arr), function(index, value) {
					$(value).delay(150 * ++j/1).fadeIn(450);
				});
			}
		});
	},
	getPage: function(page, pageCount){
		if (page == 1){
			$('.previous').hide();
		}
		if ( 1 >= (pageCount)){
			$('.next').hide();
		}
		if (page >= (pageCount)){
			$('.next').hide();
		}
	},
	submitUpload: function(){
		$( "#submit" ).click( function(event) {
			var height = $(document).height();
			$("#overlay").height(height);
		});
	},
	shuffle: function(arr) {
		var r_i;
		var v;
		for (var i = 0; i < arr.length-1; i++) {
			r_i = this.random(0, arr.length-1);
			v = arr[r_i];
			arr[r_i] = arr[arr.length-1];
			arr[arr.length-1] = v;
		}
		return arr;
	},
	random: function(min, max) {
		var range = max - min + 1;
		return Math.floor(Math.random()*range) + min;
	}
}